;
(function (call) {
    var stnf = {
        mapId: "tjMap",
        playList: null,
        latestTime: null,
        especPro:['FREMAT','TIMELAGGED'],
		stationIds: "54517,54527,54622,54623,A2967,A3169,A3364,A3507,A3590",
        router: {
            cfg: "/business/kgyb/json/stnf.json",
			getAwsStatData: 'stnData/querySTNFromSignAgaSignEleAndMultSta',
            gridData: 'objAlg/queryModelGridData',
            gridDataNew:'objAlg/queryModelGridDataNew',
            getLatestTime: 'sjyb/queryModelGridDataLatestTime',
            especGetData:'zhfx/mic4Reader/queryRainM4Data',
            especLastTime:'zhfx/mic4Reader/queryRainMic4LatestTime'
        },
        init: function () {
            var that = this;
            $.getJSON(that.router.cfg, function (cfg) {
                if (cfg) {
					debugger
                    that.buildContainer(cfg);
                    //$(".product-stnf-datepicker #stnfDate").attr("hType","H3");
                    that.bindEvt();
                }
            })
        },
        // 获取最新起报时间
        getLatestTime: function (pro) {
			var that = this;
            
            if(pro && pro.hType == "H3"){
                $(".product-stnf-datepicker .iPicker-hourWrap ul li").show();
            }else{
                $(".product-stnf-datepicker .iPicker-hourWrap ul li").hide();
                $(".product-stnf-datepicker .iPicker-hourWrap ul li[channel = '08']").show();
                $(".product-stnf-datepicker .iPicker-hourWrap ul li[channel = '20']").show();
            }
           if(pro && that.especPro.indexOf(pro.ele_id) != -1){
                var param = {
                    mode: pro.ele_id
                };
                $.ajax({
                    url: that.router.especLastTime,
                    type: 'GET',
                    dataType: 'stnfon',
                    async: false,
                    data: param
                }).done(function (res) {
                    if (res.isSuccess && res.data) {
                        that.latestTime = res.data;
                        $(".product-stnf-datepicker #stnfDate").IDatePicker().setVal(that.latestTime);
                    }
                })
            }else{
                //（昨天08） 08    （昨天20） 20  （今天08）
                let hours = 08;
                var hour = new Date().getHours();
                if(hour >=08 && hour <=20){
                    hours = 20;
                }
                if(hour <20){
                    that.latestTime = new Date(new Date(new Date().getTime() - 24*60*60*1000).setHours(hours)).format('yyyy-MM-dd hh:00:00');
                }else{
                    that.latestTime = new Date(new Date().setHours(hours)).format('yyyy-MM-dd hh:00:00');
                }
                $(".product-stnf-datepicker #stnfDate").IDatePicker().setVal(that.latestTime);
            }
			
           /** var param = {
                modeType: "EC"
            };
            $.ajax({
                url: this.router.getLatestTime,
                type: 'GET',
                dataType: 'stnfon',
                async: false,
                data: param
            }).done(function (res) {
                if (res.isSuccess && res.data) {
                    that.latestTime = res.data;
                    $(".product-stnf-datepicker #stnfDate").IDatePicker().setVal(that.latestTime);
                }
            })*/
        },
        /**
         * 构建弹出框内容
         */
        buildContainer: function (data) {
            var that = this;
            if (!data) {
                return;
            }
            data.pro_type.forEach(function (item) {
                var $li = $(`<li>${item.name}</li>`);
                $li.data('model', item);
                $li.off().click(function () {
                    if ($(this).hasClass("active")) {
                        return;
                    }
                    that.delAllLayer(); //切换模式后, 清空之前模式数据
                    $(this).addClass("active").siblings().removeClass("active");
                    $('.product-stnf-datepicker').empty()
                        .append(`
						<div class="date-panel">
							<input class="DateAgent" id="stnfDate" data-options="${item.dateOptions}" value="">
							<i class="btn-forward"></i>
							<i class="btn-backward"></i>
							<i class="btn-newest"></i>
						</div>`);
                    $.IDate(".product-stnf-datepicker .date-panel", {
                        query: function query() {
                            stnf.buildLastTime(function () {
                                stnf.queryEleData();
                            });
                        }
                    });
                    that.getLatestTime(function (latestTime) {
                        if (latestTime)
                            $(".product-stnf-datepicker #stnfDate").IDatePicker().setVal(latestTime);
                        that.buildLastTime();
                        $(".product-stnf-list").find('li.default').trigger('click');
                    });
                    that.buildProContent(data.basic_pro[item.id] || []);
                })
                $(".product-stnf-tab ul").append($li);
            })
        },
        /**
         * 构建要素展示
         * data 要素列表
         */
        buildProContent: function (data) {
            var that = this;
            $(".product-stnf-list").empty();
            data.forEach(function (item) {
                var $item = $('<div>').addClass('product-item');

                var $title = $('<div>').addClass('product-title');
                $title.data('type', item.group_id);
                $title.html(item.group_name);

                if (!item.content) {
                    that.buildCustomPro($item);
                    $title.append('<i></i>');
                }
                $item.append($title);

                if (item.content) {
                    var $ul = $('<ul>');
                    item.content.forEach(function (pro) {
                        var $li = $(`<li><span>${pro.ele_name}</span></li>`);
                        if (pro.selected)
                            $li.addClass("default");
                        $li.data('pro', pro);
                        if (pro.title)
                            $li.attr('title', pro.title);
                        if (pro.width)
                            $li.css("width", pro.width);
                        $ul.append($li);
                    })
                    $item.append($ul);
                }
                $(".product-stnf-list").append($item);
            })
        },
        buildLastTime: function (call) {
            var baseDate = $(".product-stnf-datepicker #stnfDate").IDatePicker().getVal() + ":00";
            if (this.playList) {
                this.playList.init({
                    curDate: baseDate
                });
                if ($.isFunction(call))
                    call();
            }
        },
        // 初始化播放列表
        initPlayList: function (pro) {
            var that = this;
            var startTime = pro.time;

            var layers = that.getModels(pro.ele);
            var interval = pro.ele.interval*60 || 60*1;
            this.playList = CafeJS.Timeline2({
                appendTo: "#a-m-timeline",
                curDate: startTime,
                type: 1,
                pro: pro,
                maxHour: pro.ele.maxHour || 240,
                dateOpt: {
                    dateFmt: 'yyyy-MM-dd hh:mm',
                    timeInterval: interval,
                    customHm: []
                },
                timeInterval: interval,
                layers: layers,
                gisId: that.mapId,
                call: function (pro) {
                    pro.forecastTime = that.playList.getCurTime();
                    CafeJS.layerManage.updateLayer(pro);
                    that.queryEleData(pro.ele);
                },
                getPlayData: function (pro, timeArr) {
                    that.queryEleData(pro.ele, timeArr);
                }
            });
            pro.forecastTime = that.playList.getCurTime();
            if (CafeJS.layerManage)
                CafeJS.layerManage.updateLayer(pro);
        },
		// 清除单要素GIS图层
		clearLayer: function (eleid) {
			debugger;
			GIS.Station.eleShowControl(this.mapId, [0, 1, 2, 3, 4, 5], eleid, "delete");
		},
		// 查询要素数据
		queryEleData: function (ele, time) {
			debugger
			var that = this;
			var ptype = ele.type;
			that.clearLayer([ptype]);
			that.queryAwsStatData(ele, time);
		},
		queryAwsStatData: function (ele) {
			var that = this;
			var time = $(".product-stnf-datepicker #stnfDate").IDatePicker().getVal()+":00:00";
			var element = ele.ele_id;
			//var foreTime = '2023072520';
			//var aging = '10';
			var queryTime = that.playList.getCurTime() + ":00";
            var qbTime = new Date(time).format('yyyy-MM-dd hh:mm:00');
            var agings = (new Date(queryTime).getTime() - new Date(qbTime).getTime()) / 1000 / 60 / 60;
            var foreTime = new Date(qbTime).format('yyyyMMddhh');

			$.ajax({
				url: that.router.getAwsStatData+"?element="+element+"&stationIds="+that.stationIds+"&foreTime="+foreTime+"&aging="+agings,
				type: "POST",
				contentType: 'application/json',
				success: function (res) {
					var data = res; 
					if (!data || data.length === 0){
						alert("该时间点"+ele.ele_name+"没有数据");
						return
					};
					var eleType = ele.type;
					var statTypes = [0, 1, 2, 3, 4, 5], dataArr = {};
					statTypes.forEach(function (type, index) {
						dataArr[type] = {};
					})
					data.forEach(function (station, index) {
						if (!station.lon) return;
						station.val = station.value1;
						station.val2 = station.value2;
						station.stationType = 0;
						if (station.val >= 999990) return;
						if (eleType == 'TP'){
							if (station.val == 0){
								return;
							};
							station.val = parseFloat(station.val.toFixed(1))
						};
						station.options = {
							labelStyle: $.extend(false, { fillStyle: that.getLabelObj(eleType).scolor, size: 14, textAlign: "center" }, that.getLabelObj(eleType)),
							bgStyle: { fillStyle: "rgba(0,0,0,0)", strokeStyle: "rgba(0,0,0,0)", radius: 3 }
						}
						if (dataArr[station.stationType][eleType]) {
							dataArr[station.stationType][eleType].push(station)
						} else {
							dataArr[station.stationType][eleType] = [];
							dataArr[station.stationType][eleType].push(station)
						}
					})
					var statArr = [];
					statTypes.forEach(function (type, index) {
						if ($.isEmptyObject(dataArr[type])) {
							delete dataArr[type];
						} else {
							statArr.push(type);
						}
					})
					if (statArr.length === 0) {
						return;
					}
					var dataObj = {
						dataArr: dataArr,
						eleTypes: [eleType],
						statTypes: statArr
					}
                    debugger
					GIS.Station.showElements(that.mapId, dataObj, that.getStatStyleObj(), {}, null, null, { 'cx': true });
					GIS.Station.eleShowControl(that.mapId, CafeJS.tqfx.toolsBar.getUnActiveStationType(), ['WIND', 'VIS', 'TMP', 'TP', 'RH', 'SP'], 'hide');
					if (eleType == 'WIND') {
						CafeJS.tqfx.statSignControl(CafeJS.tqfx.toolsBar.isToolActive('windbar'), "");
						CafeJS.tqfx.statSignControl(CafeJS.tqfx.toolsBar.isToolActive('windspeed'), "TxtBg");
					}
					// 站点详情
					GIS.MouseEvent.Bind(that.mapId, that.getStatLayerIds(), function(stationInfo) {
						window.stnfanalysis = {
							"stationId": stationInfo.stationId,
							"currentTime": "2023-07-25 20:00:00",
						};
						CafeJS.tqfx.showStnfDateAnalysis("stnfdateAnalysis");
					}, function(stationInfo) {
						return stationInfo.stationName;
					}); 
				},
				error: function () {
					loading.remove();
				}
			})
		},
		// 获取站点类型样式
		getStatStyleObj: function () {
			var styleObj = {
				minLevel: 0,
				size: 8,
				font: { color: { a: 1, r: 1, g: 0, b: 0 }, xOffset: 0, yOffset: 20, size: '16px', length: 18, width: 8 }
			};
			return {
				//基本站
				0: $.extend(false, styleObj, { color: { r: 224, g: 10, b: 10, a: 255 }, size: 8 }),
				//区域站
				1: $.extend(false, styleObj, { color: { r: 76, g: 77, b: 78, a: 255 }, size: 6 }),
				//海岛站
				2: $.extend(false, styleObj, { color: { r: 0, g: 0, b: 0, a: 255 }, size: 8 }),
				//浮标站
				3: $.extend(false, styleObj, { color: { r: 0, g: 0, b: 0, a: 255 }, size: 8 }),
				//船舶站
				4: $.extend(false, styleObj, { color: { r: 0, g: 0, b: 0, a: 255 }, size: 8 }),
				//平台站
				5: $.extend(false, styleObj, { color: { r: 0, g: 0, b: 0, a: 255 }, size: 8 })
			};
		},
		// 获取要素样式
		getLabelObj: function (eleType) {
			var labelObj = {
				"WIND": { xOffset: 0, yOffset: 0, scolor: "rgb(0,0,0)" },
				"VIS": { xOffset: 35, yOffset: 20, scolor: "rgb(70,135,33)" },
				"TMP": { xOffset: 0, yOffset: 20, scolor: "rgb(200,30,70)" },
				"TP": { xOffset: 35, yOffset: 0, scolor: "rgb(74,140,84)" },
				"RH": { xOffset: 0, yOffset: -20, scolor: "rgb(101,83,215)" },
				"SP": { xOffset: 35, yOffset: -20, scolor: "rgb(157,78,231)" }
			}
			return labelObj[eleType];
		},
        //获取要素样式
        getModels: function (pro) {
            var models = [];
            $.each(pro.models.split(","), function (i, m) {
                var layerId = "stnf-layer-" + m + "-" + pro.ele_id;
                models.push({
                    type: m,
                    visible: true,
                    uv: false,
                    wd: true,
                    cacheConfig: 'noCache',
                    id: layerId
                });
            });
            return models;
        },
        // 增加产品图层
        addLayerManage: function (proInfo) {
            var that = this;
			debugger
            if (CafeJS.layerManage) {
                CafeJS.layerManage.addLayer(proInfo);
            } else {
                CafeJS.layerManage = CafeJS.LayerManage({
                    appendTo: "#c-b-layermanage",
                    mapId: that.mapId,
                    proInfo: proInfo,
					isGrid:false,
                    call: function (pro) {
                        CafeJS[pro.bussitype].initPlayList(pro);
                    },
                    close: function (pro) {
                        CafeJS[pro.bussitype].delLayer(pro);
                    }
                })
            }
            
        },
		// 获取站点GIS图层id
		getStatLayerIds: function () {
			var layerIds = [];
			$(".product-stnf-list li.active").each(function () {
				var eleid = $(this).data("pro").type;
				[0, 1, 2, 3, 4, 5].forEach(function (st) {
					layerIds.push(eleid + st + "Stat");
				});
			});
			return layerIds;
		},
        // 删除图层后取消要素选择
        delLayer: function (pro) {
            var eleid = pro.ele.ele_id;
            $(".product-stnf-list li.active").each(function () {
                if ($(this).data('pro').ele_id == eleid) {
                    $(this).click();
                    return false;
                }
            })
        },
        // 删除该模式所有的要素数据
        delAllLayer: function () {
            $(".product-stnf-list li.active,.product-stnf-list td.active").each(function () {
                $(this).click();
            })
        },
        // 移除当前要素的图层
        removeLayer: function (ele) {
            var proInfo = this.getProInfo(ele);
            CafeJS.layerManage.removeLayer(proInfo);
        },
        getProInfo: function (ele) {
            var name = ele.ele_name;
            var time = $(".product-stnf-datepicker #stnfDate").IDatePicker().getVal() + ':00';
            var proInfo = {
                name: name,
                time: time,
                bussitype: 'stnf',
                ele: ele,
                isGrid: false,
                isSK: false
            }
            return proInfo;
        },
        // 清除格点图层
        clearGridLayer: function (ele_id) {
            var layerIds = [];
            if (!ele_id) return;
            GLMap.layerIds.forEach(function (layerId) {
                if (layerId.indexOf('stnf-layer') != -1 && layerId.indexOf(ele_id) != -1) {
                    layerIds.push(layerId);
                }
            })
            GIS.LayerControll.deleteLayer(this.mapId, layerIds);
        },
        getRadiu:function(){
            let item = $(".product-stnf-content .product-stnf-list li.active");
            var radiu = 0;
            if(item && item.length>0 && item.data("pro").hType == "H12"){
                radiu = 4;
            }
            return radiu;
        },
        /**
         * 绑定事件操作
         */
        bindEvt: function () {
            var that = this;
            // 要素点击事件
            $(".product-stnf-list").off('click').on('click', 'li', function () {
                var pro = $(this).data('pro');
                if ($(this).hasClass("active")) {
                    $(this).removeClass("active");
                    that.clearLayer([pro.type]);
                    that.removeLayer(pro);
                } else {
                    $(this).siblings('li.active').click(); // 清除之前选中的

                    $(this).addClass("active");
                    //that.getLatestTime(pro);
                    var proInfo = that.getProInfo(pro);
                    // 增加产品图层
                    that.addLayerManage(proInfo);
                    that.queryEleData(proInfo.ele);
                }
            })
            $('.product-stnf-datepicker').off('click').on('click', '.btn-forward', function (e) { // 日期向前
                e.stopPropagation();
                let radiu = that.getRadiu();
                $(".product-stnf-datepicker #stnfDate").IDatePicker().toForward(radiu);
                that.buildLastTime(function () {
                    that.queryEleData();
                });
            }).on('click', '.btn-backward', function (e) { // 日期向后
                e.stopPropagation();
                let radiu = that.getRadiu();
                $(".product-stnf-datepicker #stnfDate").IDatePicker().toBackward(radiu);
                that.buildLastTime(function () {
                    that.queryEleData();
                });
            }).on('click', ".btn-newest", function (e) { // 最新
                e.stopPropagation();
                $(".product-stnf-datepicker #stnfDate").IDatePicker().toNewest();
                that.buildLastTime(function () {
                    that.queryEleData();
                });
            });
            $(".product-stnf-tab li").first().click();
        }
    }
    if (typeof call === 'function') {
        CafeJS.stnf = stnf;
        call(stnf);
    }
    window.stnf = stnf;
})(function (stnf) {
    CafeJS.models(['ajax', 'legentconfig', 'legentpicker', 'timeLine2'], function () {
        stnf.init();
    });
});
